#include <QtGui>

#include "diagramTextItem.h"
#include "diagram.h"

diagramTextItem::diagramTextItem(QGraphicsItem *parent, QGraphicsScene *scene)
: QGraphicsTextItem(parent, scene)
{
	setFlag(QGraphicsItem::ItemIsSelectable);
	setZValue(1000.0);
    setTextInteractionFlags(Qt::NoTextInteraction);
}
diagramTextItem::diagramTextItem(QPointF pos, QString text,QGraphicsItem *parent, QGraphicsScene *scene)
: QGraphicsTextItem(parent, scene)
{
	setFlag(QGraphicsItem::ItemIsSelectable);
	setZValue(1000.0);
    setTextInteractionFlags(Qt::NoTextInteraction);
	setPos(pos);
	setPlainText(text);
	mText = text;
}

QVariant diagramTextItem::itemChange(GraphicsItemChange change, const QVariant &value)
{
    if (change == QGraphicsItem::ItemSelectedHasChanged){
        if ( parentItem() != NULL)
		{
			if (parentItem()->type() == box::Type)
                                focusOutEvent(new QFocusEvent(QEvent::FocusOut));
			if (parentItem()->type() == link::Type)
				if( isSelected() )
					qgraphicsitem_cast<link *>(parentItem())->visPart->setPen(QPen(QBrush(Qt::black),2));
				else
					qgraphicsitem_cast<link *>(parentItem())->visPart->setPen(QPen());
		}
		else
			 focusOutEvent(new QFocusEvent(QEvent::FocusOut));
	}
	return value;
}

void diagramTextItem::focusOutEvent(QFocusEvent *event)
{
	QGraphicsTextItem::focusOutEvent(event);
	
	if(toPlainText().right(3)!="...")
		mText = toPlainText();
	
	if(toPlainText() == "")
	{
		setPlainText(QString("          "));
	}

	setTextInteractionFlags(Qt::NoTextInteraction);
	if(parentItem()!=0){
		if(parentItem()->type() == box::Type){
			qgraphicsitem_cast<box *>(parentItem())->TextChanged();
			cutOffText();
			
		}
		else if(parentItem()->type() == link::Type) 
			qgraphicsitem_cast<link *>(parentItem())->TextChanged();
	}
        else if (scene()!=0) ((diagram*)scene())->name = mText;

		this->update();
}
void diagramTextItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
{
	if (textInteractionFlags() == Qt::NoTextInteraction)
		setTextInteractionFlags(Qt::TextEditorInteraction);

	if(parentItem()!=NULL && parentItem()->type() == box::Type) setPlainText(mText);

	QGraphicsTextItem::mouseDoubleClickEvent(event);
}

void diagramTextItem::keyPressEvent ( QKeyEvent * event )
{
	if(parentItem()!=NULL)
	{
		if(parentItem()->type() == box::Type)
		{
			switch(event->key())
			{
				case Qt::Key_Enter:
					focusOutEvent(&QFocusEvent(QEvent::FocusOut));
					break;
				case Qt::Key_Return:
					focusOutEvent(&QFocusEvent(QEvent::FocusOut));
					break;
				default:;
			}
		}
	}
	
	QGraphicsTextItem::keyPressEvent(event);
}
void diagramTextItem::cutOffText()
{
	if(mText.size()>13)
		setPlainText(mText.left(13) + QString("..."));
	setToolTip(mText);
}